#Author：雨霁夜茶

import requests
import json
import re
import time
import threading
data_dict_bittrex={}
keys=set()
import numpy as np
data_value=0

lock = threading.RLock()
def load_bittrex_b_USA():
    try:
        res = requests.get("https://bittrex.com/api/v2.0/pub/Markets/GetMarketSummaries?_=1498273180241")
        lock.acquire()
        text = json.loads(res.text)
        count = len(text['result'])
        btc_price=0
        np.set_printoptions(suppress=True)
        for i in range(count):
            content = text['result'][i]['Summary']
            data_value = float(content['Last'])

            if 'USDT-' in content['MarketName']:
                key = content['MarketName'].replace('USDT-', '').lower()
                if key == 'btc':
                    data_dict_bittrex[key] = {'usdt': data_value, 'btc': 1, 'precent': 0}
                    btc_price = data_value
                    break

        for i in range(count):
            content=text['result'][i]['Summary']
            # print(content['MarketName'],content['Last'])
            data_value=float(content['Last'])
            key=content['MarketName'].lower().split('-')[1]
            if 'USDT-' in content['MarketName']:
                keys.add(key)
                data_dict_bittrex[key]={'key':key,'usdt':data_value,'btc':0,'precent':0}
        for i in range(count):
            content = text['result'][i]['Summary']
            # print(content['MarketName'],content['Last'])
            data_value = float(content['Last'])
            key = content['MarketName'].lower().split('-')[1]
            if 'BTC-' in content['MarketName']:
                keys.add(key)
                if data_dict_bittrex.get(key) != None:
                    data_dict_bittrex.get(key)['btc'] = data_value
                    # print(data_dict_bittrex.get(key))
                else:
                    data_dict_bittrex[key] = {'key': key, 'usdt': data_value * btc_price, 'btc': data_value,
                                              'precent': 0}
        data_dict_bittrex['btc']['btc']=1
        lock.release()
        print('下载成功：Bittrex')
        return data_dict_bittrex,keys
    except requests.exceptions.RequestException:
        print('RequestException Bittrex')
        return data_dict_bittrex, keys
    except requests.exceptions.ConnectionError:
        print('ConnectionError Bittrex')
        return data_dict_bittrex, keys
    except :
        print('Error Bittrex')
        return data_dict_bittrex, keys

if __name__ == "__main__":
    load_bittrex_b_USA()
    for k,v in data_dict_bittrex.items():
        print(v)